'use strict';
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
    TextInput,
    ListView,
    RefreshControl,
    Platform,
    TouchableWithoutFeedback
} from 'react-native';
import Global from '../Commom/GlobalConst';
import ScrollableTabView, {
    DefaultTabBar,
    ScrollableTabBar
} from 'react-native-scrollable-tab-view';
import Toast from '../Utils/toast';
import CountryHomePage from './CountryHomePage';
import StayDetailsPage from './StayDetailsPage';
import SpecialtyDetailsPage from './SpecialtyDetailsPage';
import PlayDetailsPage from './PlayDetailsPage';
import DestinationAPIService from '../Commom/DestinationAPIService';
export default class SearchDestinationPage extends Component {
    constructor(props) {
        super(props);
        var dataSourceListData = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dataSourceListDataBuOne = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dataSourceListDataBuTwo = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dataSourceListDataBuThree = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dataSourceListDataBuFour = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var searchHistoryData = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSourceList: dataSourceListData,
            dataSourceListByOne: dataSourceListDataBuOne,
            dataSourceListByTwo: dataSourceListDataBuTwo,
            dataSourceListByThree: dataSourceListDataBuThree,
            dataSourceListByFour: dataSourceListDataBuFour,
            listDataType: 0,
            isRefreshing: false,
            isAnimating: false,
            searchSource: searchHistoryData,
            historyList: [],
            txtSearch: '',
        };
        this.fetchHistoryData = this.fetchHistoryData.bind(this);
        this.footerView = this.footerView.bind(this);
        this.searchHistoryRow = this.searchHistoryRow.bind(this);
        this.showResult = this.showResult.bind(this);
    }

    BackAction() {
        this.props.navigator.pop();
    }

    ClickAction(number, id) {
        switch (number) {
            case 0:
                //乡村主页
                this.props.navigator.push({
                    id: 'CountryHomePage',
                    component: CountryHomePage,
                    passProps: {
                        ID: id
                    },
                });
                break;
            case 1:
                //游玩主页
                this.props.navigator.push({
                    id: 'PlayDetailsPage',
                    component: PlayDetailsPage,
                    passProps: {
                        ID: id
                    },
                });
                break;
            case 2:
                //特产主页
                this.props.navigator.push({
                    id: 'SpecialtyDetailsPage',
                    component: SpecialtyDetailsPage,
                    passProps: {
                        ID: id
                    },
                });
                break;
            case 3:
                //住宿主页
                this.props.navigator.push({
                    id: 'StayDetailsPage',
                    component: StayDetailsPage,
                    passProps: {
                        ID: id
                    },
                });
                break;
        }
    }


    closeKeybord() {
        TextInput.State.blurTextInput(TextInput.State.currentlyFocusedField());
    }

    componentDidMount() {
        this.fetchHistoryData();
    }

    fetchHistoryData() {
        storage.load({
            key: Global.Const.storagekeySearch,
        }).then((ret) => {
            this.setState({
                historyList: ret.searchtxt,
                searchSource: this.state.searchSource.cloneWithRows(ret.searchtxt)
            });
        }).catch((err) => {
        });
    }

    searchDestination() {
        this.closeKeybord();
        storage.load({
            key: Global.Const.storagekeySearch,
        }).then(ret => {
            ret.searchtxt.push(this.state.txtSearch);
            this.setState({historyList: ret.searchtxt});
            storage.save({
                key: Global.Const.storagekeySearch,
                rawData: {
                    searchtxt: ret.searchtxt
                }
            });
            this.showResult(this.state.txtSearch);
        }).catch(err => {
            var listSearch = [];
            listSearch.push(this.state.txtSearch);
            storage.save({
                key: Global.Const.storagekeySearch,
                rawData: {
                    searchtxt: listSearch
                }
            });
            this.showResult(this.state.txtSearch);
        });
    }

    clearHistory() {
        storage.remove({
            key: Global.Const.storagekeySearch
        });
        this.setState({
            historyList: [],
            searchSource: this.state.searchSource.cloneWithRows([])
        });
    }

    showResult(searchkey) {
        DestinationAPIService.searchDestinationlist('珠海', searchkey, 1).then((ret)=> {
            var allData = ret;
            var nowListDataOne = [];
            var nowListDataTwo = [];
            var nowListDataThree = [];
            var nowListDataFour = [];
            for (let i = 0; i < allData.length; i++) {
                if ((allData[i].type) == 0) {
                    nowListDataOne.push(allData[i]);
                }
            }
            for (let i = 0; i < allData.length; i++) {
                if ((allData[i].type) == 1) {
                    nowListDataTwo.push(allData[i]);
                }
            }
            for (let i = 0; i < allData.length; i++) {
                if ((allData[i].type) == 2) {
                    nowListDataThree.push(allData[i]);
                }
            }
            for (let i = 0; i < allData.length; i++) {
                if ((allData[i].type) == 3) {
                    nowListDataFour.push(allData[i]);
                }
            }
            this.setState({
                dataSourceList: this.state.dataSourceList.cloneWithRows(ret),
                dataSourceListByOne: this.state.dataSourceListByOne.cloneWithRows(nowListDataOne),
                dataSourceListByTwo: this.state.dataSourceListByTwo.cloneWithRows(nowListDataTwo),
                dataSourceListByThree: this.state.dataSourceListByThree.cloneWithRows(nowListDataThree),
                dataSourceListByFour: this.state.dataSourceListByFour.cloneWithRows(nowListDataFour),
            });
        }).catch((err)=> {

        });

    }

    //刷新数据
    onRefreshData() {
        this.setState({
            isRefreshing: true,
            isAnimating: true
        });
        this.timer = setTimeout(
            () => {
                this.onFetch();
            },
            3000
        );
    }

    //刷新数据成功
    onFetch() {
        this.setState({
            isRefreshing: false,
            isAnimating: false,
        });
        Toast.show('刷新成功');
    }

    //加载更多数据
    loadMoreData() {
        this.setState({
            isRefreshing: true,
            isAnimating: true
        });
        this.timer = setTimeout(
            () => {
                this.endShowLoadData();
            },
            3000
        );
    }

    //加载更多数据完成
    endShowLoadData() {
        this.setState({
            isRefreshing: false,
            isAnimating: false,
        });
        Toast.show('木有更多数据');
    }


    //列表数据显示类型
    listDataType(postion) {
        if (postion == 0 || postion == 1 || postion == 2 || postion == 3 || postion == 4) {
            this.setState({
                listDataType: postion,
            });
        }
    }

    //text标签view
    labelTextView(type) {
        if (this.state.listDataType == 0) {
            switch (type) {
                case 0:
                    return (
                        <View
                            style={{position:'absolute',right:12,top:8,width:18,height:18}}>
                            <Image
                                style={{width:18,height:18,resizeMode:'contain'}}
                                source={ require('../../Image/main/icon_rural_green.png')}></Image>
                        </View>
                    )
                    break;
                case 1:
                    return (
                        <View
                            style={{position:'absolute',right:12,top:8,width:18,height:18}}>
                            <Image
                                style={{width:18,height:18,resizeMode:'contain'}}
                                source={ require('../../Image/main/icon_fun_yellow.png')}></Image>
                        </View>
                    )
                    break;
                case 2:
                    return (
                        <View
                            style={{position:'absolute',right:12,top:8,width:18,height:18}}>
                            <Image
                                style={{width:18,height:18,resizeMode:'contain'}}
                                source={ require('../../Image/main/icon_specialty_purple.png')}></Image>
                        </View>
                    )
                    break;
                case 3:
                    return (
                        <View
                            style={{position:'absolute',right:12,top:8,width:18,height:18}}>
                            <Image
                                style={{width:18,height:18,resizeMode:'contain'}}
                                source={ require('../../Image/main/icon_zhusu_pink.png')}></Image>
                        </View>
                    )
                    break;
            }
        } else {
            return null;
        }

    }


    ResultsListRow(rowData) {
        return (
            <View style={{backgroundColor:'white'}}>
                <TouchableOpacity activeOpacity={0.5}
                                  onPress={()=>this.ClickAction(rowData.type,rowData.rural_id)}>
                    <View
                        style={{width:Global.Const.size.width,height:105,flexDirection:'row',alignItems:'center',backgroundColor:'white'}}>
                        <Image style={{width:80,height:80,marginLeft:10,marginRight:10}}
                               source={{uri:rowData.rural_image}}></Image>
                        <View style={{width:Global.Const.size.width-100,height:100}}>
                            <Text
                                style={{fontSize:14,color:Global.FontColor.DimGray,marginTop:12}}>{rowData.rural_title}</Text>
                            <View style={{flexDirection:'row',marginTop:10,alignItems:'center'}}>
                                <Text style={{fontSize:12,color:Global.FontColor.DarkGray}}>{rowData.town}</Text>
                                <View
                                    style={{height:12,width:1,backgroundColor:Global.FontColor.LightGrey,marginLeft:5,marginRight:5}}></View>
                                <Text style={{fontSize:12,color:'red'}}>{rowData.been_to}</Text>
                                <Text style={{fontSize:12,color:Global.FontColor.DarkGray}}>人去过</Text>
                            </View>
                            <Text numberOfLines={1}
                                  style={{marginTop:8,fontSize:12,color:Global.FontColor.DarkGray}}>{rowData.introduce}</Text>
                        </View>
                        {this.labelTextView(rowData.type)}
                    </View>
                    {rowData.comments != null ? <View
                        style={{width:Global.Const.size.width-20,flexDirection:'row',backgroundColor:Global.Const.transparent,borderRadius:4,marginLeft:10,marginRight:10}}>
                        <Image
                            style={{marginTop:5,marginBottom:5,width:20,height:20,marginLeft:5,borderRadius:10,marginRight:7}}
                            source={{uri:rowData.comments.critics_head_url}}
                        ></Image>
                        <Text numberOfLines={2}
                              style={{marginTop:Platform.OS === 'android'?3:5,backgroundColor:'rgba(0,0,0,0)',marginBottom:5,lineHeight:20,fontSize:12,color:Global.FontColor.DarkGray,width:Global.Const.size.width-50}}>{rowData.comments.content}</Text>
                    </View> : null}
                    {rowData.comments != null ? <View
                        style={{marginTop:10,width:Global.Const.size.width,height:1,backgroundColor:Global.Const.transparent}}></View> :
                        <View
                            style={{marginTop:3,width:Global.Const.size.width,height:1,backgroundColor:Global.Const.transparent}}></View>}
                </TouchableOpacity>
            </View>
        );
    }

    searchHistoryRow(rowData, sectionID, rowID) {
        return (
            <View
                style={{width:Global.Const.size.width,height:40,backgroundColor:'white',justifyContent:'center' ,borderBottomWidth:1,borderColor:Global.Const.transparent}}>
                <TouchableOpacity onPress={()=>this.showResult(rowData)}>
                    <View
                        style={{width:Global.Const.size.width,height:40,backgroundColor:'white',justifyContent:'center' ,borderBottomWidth:1,borderColor:Global.Const.transparent}}>
                        <Text style={{marginLeft:15,fontSize:16}}>{rowData}</Text>
                    </View>
                </TouchableOpacity>
            </View>

        );
    }

    footerView() {
        if (this.state.historyList.length === 0) {
            return null;
        }
        else {
            return (
                <TouchableOpacity onPress={()=>this.clearHistory()}>
                    <View
                        style={{width:Global.Const.size.width,height:40,justifyContent:'center',alignItems:'center',backgroundColor:'white'}}>
                        <Text style={{fontSize:15}}>清除搜索历史记录</Text>
                    </View>
                </TouchableOpacity>
            );
        }
    }


    render() {
        if (this.state.dataSourceList.getRowCount() > 0) {
            return (
                <View style={styles.container}>
                    <View
                        style={{width:Global.Const.size.width,height:65,backgroundColor:'white'}}>
                        <View
                            style={{alignItems: 'center',marginTop:24,width:Global.Const.size.width-75,height:32,backgroundColor:'#F1EFEF',borderRadius:5,marginLeft:15, flexDirection: 'row'}}
                        >
                            <Image style={{width:15,height:15,marginLeft:8}}
                                   source={require('../../Image/search_icon.png')}></Image>
                            <TextInput style={{marginTop:-1,width:Global.Const.size.width-110,fontSize:12,marginLeft:Platform.OS === 'ios'?12:null}}
                                       onChangeText={txtSearch => this.setState({ txtSearch})}
                                       placeholder={'请选择您的目的地'}
                                       returnKeyType={'search'}
                                       enablesReturnKeyAutomatically={true}
                                       blurOnSubmit={false}
                                       underlineColorAndroid={'transparent'}
                                       onSubmitEditing={()=>this.searchDestination()}
                            ></TextInput>
                        </View>

                        <View
                            style={{justifyContent:'center', position: 'absolute',right: 0,top: 0,width:60,height:75,alignItems:'center'}}>
                            <TouchableOpacity activeOpacity={0.5}
                                              onPress={()=>this.BackAction(false)}>
                                <Text style={{ color: '#24CD78',fontSize:16}}>取消</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View
                        style={{height:2,width:Global.Const.size.width,backgroundColor:Global.Const.transparent}}></View>
                    <View style={{backgroundColor:'white',flex:1}}>
                        <ScrollableTabView
                            renderTabBar={
                            () => <DefaultTabBar
                            textStyle={{ fontSize: 13,marginTop: 8}}
                            style={{height:35,borderBottomColor: '#F5F5F5'}}/>}
                            tabBarUnderlineStyle={{backgroundColor: '#24CD78',height:3}}
                            tabBarUnderlineColor={'#FF0000'}
                            tabBarActiveTextColor={'#24CD78'}
                            tabBarInactiveTextColor={'#333333'}
                            tabBarPosition='top'
                            onChangeTab={(obj) => {
                                   this.listDataType(obj.i)
                                }
                              }
                        >
                            <View tabLabel="全部">
                                <ListView
                                    refreshControl={
                                          <RefreshControl
                                            refreshing={this.state.isRefreshing}
                                            onRefresh={() => {this.onRefreshData()}}
                                            colors={['#4CAF50', '#4CAF50', '#4CAF50', '#4CAF50']}
                                            progressBackgroundColor="white"
                                          /> }
                                    onEndReachedThreshold={50}
                                    onEndReached={() => {this.loadMoreData()}}

                                    enableEmptySections={true}
                                    dataSource={this.state.dataSourceList}
                                    renderRow={this.ResultsListRow.bind(this)}/>
                            </View>
                            <View tabLabel="乡村"
                                  style={{ flex: 1,alignItems: 'center',justifyContent: 'center',backgroundColor: '#f7f7f7'}}>
                                <ListView
                                    refreshControl={
                                          <RefreshControl
                                            refreshing={this.state.isRefreshing}
                                            onRefresh={() => {this.onRefreshData()}}
                                            colors={['#4CAF50', '#4CAF50', '#4CAF50', '#4CAF50']}
                                            progressBackgroundColor="white"
                                          /> }
                                    onEndReachedThreshold={50}
                                    onEndReached={() => {this.loadMoreData()}}

                                    enableEmptySections={true}
                                    dataSource={this.state.dataSourceListByOne}
                                    renderRow={this.ResultsListRow.bind(this)}/>
                            </View>
                            <View tabLabel="游玩"
                                  style={{ flex: 1,alignItems: 'center',justifyContent: 'center',backgroundColor: '#f7f7f7'}}>
                                <ListView
                                    refreshControl={
                                          <RefreshControl
                                            refreshing={this.state.isRefreshing}
                                            onRefresh={() => {this.onRefreshData()}}
                                            colors={['#4CAF50', '#4CAF50', '#4CAF50', '#4CAF50']}
                                            progressBackgroundColor="white"
                                          /> }
                                    onEndReachedThreshold={50}
                                    onEndReached={() => {this.loadMoreData()}}

                                    enableEmptySections={true}
                                    dataSource={this.state.dataSourceListByTwo}
                                    renderRow={this.ResultsListRow.bind(this)}/>
                            </View>
                            <View tabLabel="特产"
                                  style={{ flex: 1,alignItems: 'center',justifyContent: 'center',backgroundColor: '#f7f7f7'}}>
                                <ListView
                                    refreshControl={
                                          <RefreshControl
                                            refreshing={this.state.isRefreshing}
                                            onRefresh={() => {this.onRefreshData()}}
                                            colors={['#4CAF50', '#4CAF50', '#4CAF50', '#4CAF50']}
                                            progressBackgroundColor="white"
                                          /> }
                                    onEndReachedThreshold={50}
                                    onEndReached={() => {this.loadMoreData()}}

                                    enableEmptySections={true}
                                    dataSource={this.state.dataSourceListByThree}
                                    renderRow={this.ResultsListRow.bind(this)}/>
                            </View>
                            <View tabLabel="住宿"
                                  style={{ flex: 1,alignItems: 'center',justifyContent: 'center',backgroundColor: '#f7f7f7'}}>
                                <ListView
                                    refreshControl={
                                          <RefreshControl
                                            refreshing={this.state.isRefreshing}
                                            onRefresh={() => {this.onRefreshData()}}
                                            colors={['#4CAF50', '#4CAF50', '#4CAF50', '#4CAF50']}
                                            progressBackgroundColor="white"
                                          /> }
                                    onEndReachedThreshold={50}
                                    onEndReached={() => {this.loadMoreData()}}

                                    enableEmptySections={true}
                                    dataSource={this.state.dataSourceListByFour}
                                    renderRow={this.ResultsListRow.bind(this)}/>
                            </View>
                        </ScrollableTabView>
                    </View>
                </View>
            );
        }
        if (this.state.searchSource.getRowCount() > 0) {
            return (
                <View style={styles.container}>
                    <View
                        style={{width:Global.Const.size.width,height:65,backgroundColor:'white'}}>
                        <View
                            style={{alignItems: 'center',marginTop:24,width:Global.Const.size.width-80,height:32,backgroundColor:'#F1EFEF',borderRadius:5,marginLeft:15, flexDirection: 'row'}}
                        >
                            <Image style={{width:15,height:15,marginLeft:8}}
                                   source={require('../../Image/search_icon.png')}></Image>
                            <TextInput style={{marginTop:-1,width:Global.Const.size.width-110,fontSize:12,marginLeft:Platform.OS === 'ios'?12:null}}
                                       onChangeText={txtSearch => this.setState({ txtSearch})}
                                       placeholder={'请选择您的目的地'}
                                       returnKeyType={'search'}
                                       enablesReturnKeyAutomatically={true}
                                       blurOnSubmit={false}
                                       underlineColorAndroid={'transparent'}
                                       onSubmitEditing={()=>this.searchDestination()}
                            ></TextInput>
                        </View>

                        <View
                            style={{justifyContent:'center', position: 'absolute',right: 0,top: 0,width:65,height:75,alignItems:'center'}}>
                            <TouchableOpacity activeOpacity={0.5}
                                              onPress={()=>this.BackAction(false)}>
                                <Text style={{ color: '#24CD78',fontSize:18}}>取消</Text>
                            </TouchableOpacity>
                        </View>

                    </View>
                    <View
                        style={{height:2,width:Global.Const.size.width,backgroundColor:Global.Const.transparent}}></View>
                    <ListView
                        enableEmptySections={true}
                        dataSource={this.state.searchSource}
                        renderRow={this.searchHistoryRow}
                        renderFooter={this.footerView}
                    />
                </View>
            );
        }
        return (
            <View style={styles.container}>
                <View
                    style={{width:Global.Const.size.width,height:65,backgroundColor:'white'}}>
                    <View
                        style={{alignItems: 'center',marginTop:24,width:Global.Const.size.width-80,height:32,backgroundColor:'#F1EFEF',borderRadius:5,marginLeft:15, flexDirection: 'row'}}
                    >
                        <Image style={{width:15,height:15,marginLeft:8}}
                               source={require('../../Image/search_icon.png')}></Image>
                        <TextInput style={{marginTop:-1,width:Global.Const.size.width-110,fontSize:12,marginLeft:Platform.OS === 'ios'?12:null}}
                                   onChangeText={txtSearch => this.setState({ txtSearch})}
                                   placeholder={'请选择您的目的地'}
                                   returnKeyType={'search'}
                                   enablesReturnKeyAutomatically={true}
                                   blurOnSubmit={false}
                                   underlineColorAndroid={'transparent'}
                                   onSubmitEditing={()=>this.searchDestination()}
                        ></TextInput>
                    </View>

                    <View
                        style={{justifyContent:'center', position: 'absolute',right: 0,top: 0,width:65,height:75,alignItems:'center'}}>
                        <TouchableOpacity activeOpacity={0.5}
                                          onPress={()=>this.BackAction(false)}>
                            <Text style={{ color: '#24CD78',fontSize:18}}>取消</Text>
                        </TouchableOpacity>
                    </View>

                </View>
            </View>
        );
    }
}
var styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Global.Const.transparent,
    },
});
